package edu.uoc.tds.pec3.client;

//import java.rmi.Remote;
import java.rmi.RemoteException;
import java.sql.Date;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

import edu.uoc.tds.pec3.beans.PeticionRecurso;
import edu.uoc.tds.pec3.common.GestorEstocInterface;
import edu.uoc.tds.pec3.i18n.TDSLanguageUtils;

public class PanelAtenderPeticiones extends JPanel {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private GestorEstocInterface enlaceRemoto;
	/**
     * Creates new form Conexion
	 * @param enlaceRemoto 
	 * @throws RemoteException 
     */
    public PanelAtenderPeticiones(GestorEstocInterface enlaceRemoto) throws RemoteException {
    	this.enlaceRemoto = enlaceRemoto;
        initComponents(enlaceRemoto);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     * @param enlaceRemoto 
     * @throws RemoteException 
     */
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents(GestorEstocInterface enlaceRemoto) throws RemoteException {
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jPanel1.titulo")));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jPanel2.titulo")));        
        
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable1.col1")),
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable1.col2")),
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable1.col3")),
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable1.col4"))
            		,"idR","idA"
            }
        ) {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(5);
        jTable1.removeColumn(jTable1.getColumnModel().getColumn(4));
        jTable1.removeColumn(jTable1.getColumnModel().getColumn(4));

        jButton1.setText(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jButton1.titulo"));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jPanel3.titulo")));

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {},
            new String [] {
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable2.col1")),
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable2.col2")),
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable2.col3")),
            		(TDSLanguageUtils.getMessage("cliente.pantallaAtenderPeticiones.jTable2.col4"))
            		
            }
        ) {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(3).setPreferredWidth(5);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        
        
        pintarTabla(enlaceRemoto);
    }// </editor-fold>




    private void pintarTabla(GestorEstocInterface enlaceRemoto) {
        try {
        	List<PeticionRecurso> peticiones = enlaceRemoto.getPeticionRecursos();   
        	
        	for(PeticionRecurso e:peticiones){ 
        		
        		Format formatter = new SimpleDateFormat("yyyy-MM-dd");
        		String[] data1 = new String[6];
        		
        		data1[0] = formatter.format(e.getFechaAltaPeticion());
        		data1[1] = enlaceRemoto.getAula(e.getIdAula()).getDescripcionAula();
        		data1[2] = enlaceRemoto.getRecurso(e.getIdRecurso()).getNombreRecurso();
        		data1[3] = Integer.toString(e.getCantidad());
        		data1[4] = Integer.toString(e.getIdRecurso());
        		data1[5] = Integer.toString(e.getIdAula());
        		
        		if (e.getCantidad() > enlaceRemoto.getRecurso(e.getIdRecurso()).getCantidadStock()) {        			
        			((DefaultTableModel) jTable2.getModel()).addRow(data1);
        		} else {
        			((DefaultTableModel) jTable1.getModel()).addRow(data1);
        		}   
        	} 
        	
        	jTable1.repaint();
        	
        } catch (RemoteException e) {
        } catch (Exception e) {
        } 
    }    
    
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		//System.out.println(jTable1.getModel().getRowCount());
		if (jTable1.getModel().getRowCount() > 0) {			
			int idRecurso = Integer.parseInt((String) jTable1.getModel().getValueAt(0, 4));	
			int idAula    = Integer.parseInt((String) jTable1.getModel().getValueAt(0, 5));
			int cantidad  = Integer.parseInt((String) jTable1.getModel().getValueAt(0, 3));	
			
			String nombreAula = (String) jTable1.getModel().getValueAt(0, 1);
			String nombreRecurso = (String) jTable1.getModel().getValueAt(0, 2);
			
			int stock = 0;
			try {
				stock = enlaceRemoto.getRecurso(idRecurso).getCantidadStock();
				stock = stock - cantidad;
			} catch (RemoteException e2) {
				e2.printStackTrace();
			}
			
			
		    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 	  
		    java.util.Date date = null;
			try {
				date = formatter.parse((String) jTable1.getModel().getValueAt(0, 0));
			} catch (ParseException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    java.sql.Date fechaAltaPeticion = new Date(date.getTime());	    		
	    
	    	
	    	DefaultTableModel dm = (DefaultTableModel)jTable1.getModel();
	    	dm.getDataVector().removeAllElements();
	    	DefaultTableModel dm2 = (DefaultTableModel)jTable2.getModel();
	    	dm2.getDataVector().removeAllElements();    	    	
	    
	    	PeticionRecurso peticionRecurso = new PeticionRecurso(idRecurso, idAula, fechaAltaPeticion, cantidad, null);
	    	
	    	try {
				enlaceRemoto.atenderPeticionRecurso(peticionRecurso);
				JOptionPane.showMessageDialog(null, 
						TDSLanguageUtils.getMessage("cliente.pantallaPeticionRecurso.lblAula") + nombreAula  +
						"\n" + TDSLanguageUtils.getMessage("cliente.pantallaPeticionRecurso.lblTipoRecurso") + nombreRecurso +
						"\n" + TDSLanguageUtils.getMessage("cliente.pantallaPeticionRecurso.lblCantidadSolicitada") + cantidad  + 
						"\n" + TDSLanguageUtils.getMessage("cliente.pantallaPeticionRecurso.mensaje.stockactual") + stock, 
						TDSLanguageUtils.getMessage("cliente.pantallaPeticionRecurso.mensaje.atendido"), JOptionPane.INFORMATION_MESSAGE);  
			} catch (RemoteException e) {
				e.printStackTrace();
			}
	    	
	    	pintarTabla(enlaceRemoto);
		}
    }
	
	

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration
}
